<?php

# 获取所有章节的数据

if ( count($argv) < 2 ) {
	echo <<<EOF
Please Provide DATA_FILE_NAME
Usage :
	php -dopen_basedir=/ get_content.php ./DATA/00/1035025/DATA_RAW	
EOF;
	die();
}

$datafile = $argv[1];
$dirname = dirname ($datafile);
preg_match("/.*\/(\d+)$/", $dirname, $arr);
$book_id = ($arr[1]);

$indexfile = $dirname . "/INDEX_DONE";
$data_content = file_get_contents($datafile);

$indexes = file($indexfile);

$vols = array ();
$chaps = array ();

foreach ($indexes as $index){ 
        $index = trim($index);
        $arr = explode("|", $index);
        $chapname = $arr[0];
        $other = $arr[1];
        $cs = array ();
        $others = explode ("^", $other);
        foreach ($others as $row) {
                if (trim($row) == "") continue;
                $cs[] = array ($row, count($chaps)) ;
                $chaps[] = $row;
        }
        $vols[] = array ($chapname, $cs);
}

$chaps_data = array();
$chaps_cnt = count($chaps);
$db = new PDO("mysql:host=localhost;dbname=rainx_duanurl_com", "rainx", "TdLxXYRM");
$sth = $db->prepare("insert into qidian_chaps set content=?,  updated_time=now()");
for ($i=0; $i<$chaps_cnt; $i++)
{
	if ($i == $chaps_cnt - 1 ) {		
		$data  = strstr($data_content, $chaps[$i]);
	}
	else
	{
		$data_tmp = strstr($data_content, $chaps[$i]);
		$data = substr ($data_tmp, 0, strpos($data_tmp , $chaps[$i+1]) );
	}

	$db->query ("set names gbk");
	$chaps_data[$i] = array ("data"=> $data);
	$content = serialize( array ($data, $book_id) );
	$ret = $sth->execute( array ($content));
	$cid = $db->lastInsertId();
	$chaps_data[$i]['id'] = $cid;
}

# appand data to vols

for($i = 0; $i < count($vols); $i++){ 
	$cs = $vols[$i][1];
	for($j=0; $j < count ($cs); $j++) {
		$vols[$i][1][$j][] = $chaps_data[$vols[$i][1][$j][1]]['id'];
	}
}

$content = serialize ($vols);
$sth=$db->prepare("insert into qidian_book_index set id=? ,content=?");
$sth->execute( array ($book_id, $content) );
